/**
 * Copyright (c) 2016-2023, Michael Yang 杨福海 (fuhai999@gmail.com).
 * <p>
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl-3.0.txt
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jpress.module.article.searcher;

import com.jfinal.aop.Aop;
import io.jboot.Jboot;
import io.jboot.components.mq.JbootmqMessageListener;
import io.jboot.utils.StrUtil;
import io.jpress.module.article.model.Article;

/**
 * @author michael yang (fuhai999@gmail.com)
 * @Date: 2020/3/1
 */
public class LuceneSyncNotifier implements JbootmqMessageListener {

    private String mqClientId;

    public LuceneSyncNotifier() {
        this.mqClientId = StrUtil.uuid();
        Jboot.getMq().addMessageListener(this, "lucene-article");
    }

    public void notifyArticleAdd(Article article) {
        Jboot.getMq().publish(new LuceneSyncMessage(LuceneSyncMessage.ACTION_ADD, mqClientId, article), "lucene-article");
    }

    public void notifyArticleDelete(Object articleId) {
        Jboot.getMq().publish(new LuceneSyncMessage(LuceneSyncMessage.ACTION_DELETE, mqClientId, articleId), "lucene-article");
    }

    public void notifyArticleUpdate(Article article) {
        Jboot.getMq().publish(new LuceneSyncMessage(LuceneSyncMessage.ACTION_UPDATE, mqClientId, article), "lucene-article");
    }


    @Override
    public void onMessage(String channel, Object message) {
        LuceneSyncMessage msg = (LuceneSyncMessage) message;
        if (mqClientId.equals(msg.getClientId())) {
            return;
        }

        LuceneSearcher searcher = Aop.get(LuceneSearcher.class);
        switch (msg.getAction()) {
            case LuceneSyncMessage.ACTION_ADD:
                searcher.doAddArticle(msg.getArticle(), false);
                break;
            case LuceneSyncMessage.ACTION_DELETE:
                searcher.doDeleteArticle(msg.getArticleId(), false);
                break;
            case LuceneSyncMessage.ACTION_UPDATE:
                searcher.doUpdateArticle(msg.getArticle(), false);
                break;
        }
    }


}
